package com.songlanyun.modules.donaterecord.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.enums.DonationConstant;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.modules.donaterecord.dao.DonateRecordDao;
import com.songlanyun.modules.donaterecord.entity.DonateRecordEntity;
import com.songlanyun.modules.donaterecord.service.DonateRecordService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;


@Service("donateRecordService")
public class DonateRecordServiceImpl extends ServiceImpl<DonateRecordDao, DonateRecordEntity> implements DonateRecordService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Integer userId = MapUtil.getInt(params, "user_id");
        Integer type = MapUtil.getInt(params, "type");
        IPage<DonateRecordEntity> page = this.page(
                new Query<DonateRecordEntity>().getPage(params),
                new LambdaQueryWrapper<DonateRecordEntity>()
                        .eq(ObjectUtil.isNotNull(userId), DonateRecordEntity::getUserId, userId)
                        .eq(ObjectUtil.isNotNull(type), DonateRecordEntity::getType, type)
                        .orderByDesc(DonateRecordEntity::getCreateTime)
        );

        return new PageUtils(page);
    }

    @Override
    public void add(Long userId, DonationConstant.DonateMsgType type, String content) {
        DonateRecordEntity donateRecordEntity = new DonateRecordEntity();
        donateRecordEntity.setUserId(userId);
        donateRecordEntity.setType(type);
        donateRecordEntity.setContent(content);
        //生成证书编号    证书编号规则：年月日时分秒+XXX随机码 26位
        donateRecordEntity.setCertificateNumber(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomNumbers(12));
        this.baseMapper.insert(donateRecordEntity);
    }

}
